package com.czy.workflow.core.context;

import com.czy.workflow.core.executor.SimpleTaskExecutor;
import com.czy.workflow.core.executor.TaskExecutor;
import com.czy.workflow.core.listener.TaskListenerNotify;
import com.czy.workflow.core.service.FlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by admin on 2019/8/31.
 */

@Configuration
public class FlowBeanConfig {


    @Autowired
    ApplicationContext applicationContext;


    final int POOL_SIZE = 3;


    @Bean
    public TaskListenerNotify taskListenerNotify(){
        return new TaskListenerNotify();
    }

    @Bean(name = "threadPoolService")
    public ExecutorService executorService(){
        int cpuNumbers = Runtime.getRuntime().availableProcessors();  //获取当前系统的CPU 数目
        return Executors.newFixedThreadPool(cpuNumbers * POOL_SIZE);
    }

    @Bean
    public TaskExecutor taskExecutor(){
        return new SimpleTaskExecutor();
    }

    @Bean
    public FlowContext flowContext(FlowConfig flowConfig, TaskExecutor taskExecutor, ExecutorService threadPoolService, TaskListenerNotify taskListenerNotify){
        FlowService flowServiceBean = applicationContext.getBean(flowConfig.getStore() + "FlowService", FlowService.class);
        FlowContext flowContextBean = new FlowContext(flowConfig, taskExecutor, threadPoolService, taskListenerNotify, flowServiceBean);
        taskExecutor.setFlowContext(flowContextBean);
        taskListenerNotify.setFlowContext(flowContextBean);
        return flowContextBean;
    }


    @Bean
    public FlowComponentScan flowComponentScan(FlowContext flowContext){
        return new FlowComponentScan(flowContext);
    }

}
